//
//  ViewController.m
//  GuessTu
//
//  Created by @Zs on 15/6/28.
//  Copyright (c) 2015年 @Zs. All rights reserved.
//

#import "ViewController.h"
#import "UIView+Extension.h"
#import "Question.h"
#import "MBProgressHUD+NJ.h"
#import "UMSocial.h"
#define BtnWidth  35
#define time 0.08
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *money;
@property (weak, nonatomic) IBOutlet UILabel *labelNumber;
@property (weak, nonatomic) IBOutlet UILabel *descrip;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *fromTop;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *heightCons;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *widthCons;
@property (weak, nonatomic) IBOutlet UIButton *bgImg;
@property (assign,nonatomic) BOOL big;
@property (weak,nonatomic) UIButton *coverBtn;
@property (strong,nonatomic) NSArray *questionArray;
@property (assign,nonatomic) int index;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;

@property (weak, nonatomic) IBOutlet UIView *answerView;

@property (weak, nonatomic) IBOutlet UIView *optionView;


@property (assign,nonatomic) BOOL isFull;



//基本数据类型  bool int float double 用assign
//对象用  array 字典 用strong
//控件用weak
//字符串  用copy


@end

@implementation ViewController


#pragma mark -提示[多看]
- (IBAction)tipBtn {
    
    
    //286
    if (self.money.currentTitle.intValue >= 2000 ) {
        [self.money setTitle:[NSString stringWithFormat:@"%d",self.money.currentTitle.intValue-2000] forState:UIControlStateNormal];
        
        //1清楚所有文字内容 相当于点击了所有的答案按钮
        for (UIButton *ansBtn in self.answerView.subviews) {
            [self didSelectAnswerBtn:ansBtn];
        }
        
        // 2. 把正确答案的第一个文字显示到答案按钮, 把对应文字的待选按钮隐藏(相当于点击了第一个正确答案的待选按钮)
        
        //2.1取出答案
        Question *q = self.questionArray[self.index];
        //2.2截取答案第一个文字
        NSString *firstAnswer = [q.answer substringToIndex:1];
        //2.3 相当于点击了第一个正确答案的待选按钮
        for (UIButton *optionBtn in self.optionView.subviews) {
            
            if ([firstAnswer isEqualToString:[optionBtn currentTitle]]) {
                [self didSelectedOptionBtn:optionBtn];
                break;
            }
            
            
        }
        
        
        
        }else{
        [MBProgressHUD showError:@"积分不足!"];
        
    }
    
    
    
}
/**
 *  分享
 */
- (IBAction)share {
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"55a7a29967e58eebaf00069a"
                                      shareText:@"天天猜图带你嗨到爆"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,nil]
                                       delegate:nil];
    
}

/**
 *  大图
 */

- (IBAction)bigImgBtn {
    
    [self didClickedImg];

}



/**
 *  按钮大图不是点击图片
 */
//- (IBAction)bigImgBtn {
//    [self didClickedImg];
//}





//MARK:下一题

- (IBAction)nextQuestion {
    
    self.optionView.userInteractionEnabled = YES;
    //解决控件重复添加 被覆盖 不显示间隔
    //原理:在每次添加答案按钮的时候 把上次view上的所有子控件移除
    for (UIView *viewUsed in self.answerView.subviews) {
        [viewUsed removeFromSuperview];
    }
    
    
    //移除备选答案的重复覆盖
    for (UIView *viewAnswerUsed in self.optionView.subviews) {
        [viewAnswerUsed removeFromSuperview];
    }
    
    
    
    //索引自增
    self.index++;
    Question *question = self.questionArray[self.index];
    NSLog(@"%@",question.title);
  
    
    
    
    for (int i = 0; i<question.options.count; i++) {
        
        
        UIButton *optionBtn = [[UIButton alloc]init];
        
        [optionBtn setBackgroundImage:[UIImage imageNamed:@"btn_option"] forState:UIControlStateNormal];
        [optionBtn setBackgroundImage:[UIImage imageNamed:@"btn_option_highlighted"] forState:UIControlStateHighlighted];
        [self.optionView addSubview:optionBtn];
        CGFloat btnMargin = 10;
        //每一行有几列
        int lie = 7;
        int lieNumber = i%lie;
        int rowNumber = i/lie;
        int topMargin = 10;
        CGFloat viewW = self.view.frame.size.width;//宽度
        CGFloat leftMargin = (viewW - lie*BtnWidth - (lie-1)*btnMargin)*0.5;
        CGFloat btnX = leftMargin + (BtnWidth+10)*lieNumber;
        CGFloat btnY = topMargin +(BtnWidth+topMargin)*rowNumber;
        
        optionBtn.frame  = CGRectMake(btnX, btnY, BtnWidth, BtnWidth);
        
        [optionBtn setTitle:question.options[i] forState:UIControlStateNormal];
        [optionBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [optionBtn addTarget:self action:@selector(didSelectedOptionBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    

    //图片变动
    [self.bgImg setImage:[UIImage imageNamed:question.icon] forState:UIControlStateNormal];
    //描述
    self.descrip.text = question.title;
    
    self.labelNumber.text = [NSString stringWithFormat:@"%d/%ld",self.index+1,(unsigned long)self.questionArray.count];
    
    if (self.index == 9 ) {
        
        self.nextBtn.enabled = NO;
    }

    for (int i = 0; i<question.answer.length; i++) {
        
        UIButton *answerBtn = [[UIButton alloc]init];
        
        [answerBtn addTarget:self action:@selector(didSelectAnswerBtn:) forControlEvents:UIControlEventTouchUpInside];
        
        [answerBtn setBackgroundImage:[UIImage  imageNamed:@"btn_answer"] forState:UIControlStateNormal];
        
        [answerBtn setBackgroundImage:[UIImage  imageNamed:@"btn_answer_highlighted"] forState:UIControlStateHighlighted];
        
        [answerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        
        [self.answerView addSubview:answerBtn];
        
        int answerLength = (int)question.answer.length;
        
    
        CGFloat viewW = self.view.frame.size.width;
        CGFloat leftMargin = (viewW - answerLength*BtnWidth-(answerLength-1)*15)*0.5;
        CGFloat btnY = (self.answerView.height-BtnWidth)*0.5;

        CGFloat btnX = leftMargin + (BtnWidth+15)*i;
        
        answerBtn.frame = CGRectMake(btnX,btnY, BtnWidth, BtnWidth);
    }
    
    
}


/**
 *  点击答案按钮
 *
 *  @return <#return value description#>
 */
-(void)didSelectAnswerBtn:(UIButton *)answerBtn{

    NSString *answerTitle = [answerBtn currentTitle];
    
    for (UIButton *optionBtn in self.optionView.subviews) {
        NSString *optionTitle = [optionBtn currentTitle];
        
        if ([answerTitle isEqualToString:optionTitle] && optionBtn.hidden ==YES) {
            
            optionBtn.hidden = NO;
            break;
        }
        
        
    }
    self.optionView.userInteractionEnabled = YES;
    
    [answerBtn setTitle:nil forState:UIControlStateNormal];

    for (UIButton *b in self.answerView.subviews) {
        [b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
    
    
    
}





/**
 *  点击备选答案按钮
 */
-(void)didSelectedOptionBtn:(UIButton *)btn{
    //拿得是btn上text
//    NSLog(@"%@",btn.titleLabel.text);
    btn.hidden = YES;
    
    for (UIButton *answerBtn in self.answerView.subviews) {
        NSString *answerTitle = [answerBtn titleForState:UIControlStateNormal];
        if (answerTitle.length == 0) {
            [answerBtn setTitle:[btn titleForState:UIControlStateNormal] forState:UIControlStateNormal];
            break;
        }
        
    }
    
    

//    NSMutableArray *temp = [NSMutableArray array];
//    [temp addObject:[btn currentTitle]];
//    [temp insertObject:[btn currentTitle] atIndex:0];
        NSMutableArray *a = [NSMutableArray array];
    UIButton *myBtn = (UIButton*)self.answerView.subviews.lastObject;
    
    if ([myBtn titleForState:UIControlStateNormal].length !=0) {
        self.isFull = YES;
        
        self.optionView.userInteractionEnabled = NO;
        
        for (UIButton *btn in self.answerView.subviews) {
            NSString *btnStr = [btn currentTitle];

            [a addObject:btnStr];
        }
        
//        int coin;
        Question *q = self.questionArray[self.index];
        
        
        NSString *answerStr = [a componentsJoinedByString:@""];
        
        
        
        
        
        if ([answerStr isEqualToString:q.answer]) {
            [MBProgressHUD showSuccess:@"已对!"];
            
            if (self.index < 9) {
                [self nextQuestion];

            }[self changeScore:500];
            if (self.index == self.questionArray.count -1) {
                //创建弹框
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"超级猜图" message:@"恭喜已通关!" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:cancelAction];
                [alertController addAction:okAction];
                
                [self presentViewController:alertController animated:YES completion:nil];
                
            }
            
        }else {
            //错误答案闪烁
           
            [self wrongAnimation];
            
//            [MBProgressHUD showError:@"答错了!!"];
        }
        
        
        
    }
    
}


- (void)wrongAnimation{
    for (UIButton *b in self.answerView.subviews) {
        
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [b setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [b setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [b setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            [b setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                            
                        });
                        
                    });
                });
            });
        });
        
        
    }
}


#pragma mark 点击图片放大缩小
- (IBAction)didClickedImg {

    //动画原理:放慢执行速度

    
    if (self.big) {
        [self bigImage];
    }else{
        [self smallImg];
    }
    
}

-(NSArray *)questionArray{

    
    NSBundle *bundle = [NSBundle mainBundle];
    NSString *filePath = [bundle pathForResource:@"questions" ofType:@"plist"];
    
    
    
    
    if (_questionArray == nil) {
        NSArray *dictArray = [NSArray arrayWithContentsOfFile:filePath];
        
        NSMutableArray *tempArray = [NSMutableArray array];
        
        for (NSDictionary *dict in dictArray) {
            
            Question *question = [Question questionWithDic:dict];
            [tempArray addObject:question];
            
        }
        _questionArray  = tempArray;
        
        
    }
    
    
    return _questionArray;
    
}

/**
 *  改变分数
 *
 *  @param changeScore <#changeScore description#>
 */
-(void)changeScore:(int)changeScore{

    NSString *targetTitle = [self.money currentTitle];
   
    int targetScore = [targetTitle intValue];
    
    targetScore+=changeScore;
    
    [self.money setTitle:[NSString stringWithFormat:@"%d",targetScore] forState:UIControlStateNormal];
    
    
    
}




#pragma mark 大图
- (void)bigImage{
    
    UIButton *cover = [[UIButton alloc]init];
    
    self.coverBtn = cover;
    [self.view addSubview:cover];
    
    //window 包含整个窗口(带导航栏)  view是包含整个你能看到的
    cover.frame = [UIApplication sharedApplication].keyWindow.bounds;
    
    [cover setBackgroundColor:[UIColor blackColor]];
    //设置蒙版透明度
    cover.alpha = 0.5;
    
    
    [self.coverBtn addTarget:self action:@selector(didClickedCover) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view bringSubviewToFront:self.bgImg];
    
    
    self.big = NO;
    [UIView animateWithDuration:0.35 animations:^{

        self.heightCons.constant = [UIScreen mainScreen].bounds.size.width;
        
        self.widthCons.constant = self.heightCons.constant;
        
        self.fromTop.constant = ([UIScreen mainScreen].bounds.size.height-self.widthCons.constant);
        
        [self layoutSubviews];
        
    }];
}


- (void)layoutSubviews{
    // 如果改变约束,强制更新
    [self.bgImg layoutIfNeeded];
    [self.optionView layoutIfNeeded];
    [self.answerView layoutIfNeeded];

}

/**
 *  蒙版部分点击缩小图片
 */
-(void)didClickedCover{

    [self smallImg];

}

/**
 *  图片缩小
 */
- (void)smallImg{
    self.big = YES;
    [UIView animateWithDuration:0.35 animations:^{
        self.heightCons.constant = 150;
        self.widthCons.constant = 150;
        self.fromTop.constant = -135;
        [self.coverBtn setBackgroundColor:[UIColor clearColor]];//蒙版颜色清除
        [self layoutSubviews];
        [self.coverBtn removeFromSuperview ];// self.cover == nil;缩小图片的时候清楚蒙版
    }];
}

#pragma mark - 控制状态栏的样式
- (UIStatusBarStyle)preferredStatusBarStyle
{
    
    return UIStatusBarStyleLightContent;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.big = YES;//初始化变大
    self.index = -1;//初始化调用已经加1 这里为-1
    [self nextQuestion];
    self.isFull = NO;


    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
